import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import Dropout
# Set the path to the dataset
data_folder = "C:/yas_tahmini/UTKFaceee"
# Load and process the data
files = os.listdir(data_folder)
ages = []
genders = []
images = []
for file in files:
parts = file.split('_')
if len(parts) < 3 or not parts[0].isdigit() or not parts[1].isdigit():
continue
age, gender = map(int, parts[:2])
full_path = os.path.join(data_folder, file)
image = cv2.imread(full_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (224, 224))
images.append(image)
ages.append(age)
genders.append(gender)
images_np = np.array(images) / 255
ages_np = np.array(ages)
genders_np = np.array(genders)
X_train, X_test, Y_age_train, Y_age_test, Y_gender_train, Y_gender_test = train_test_split(images_np, ages_np, genders_np, test_size=0.25)
# Load the pre-trained ResNet50 model
base_model = ResNet50(weights=None, include_top=False)
# Age Model
x_age = GlobalAveragePooling2D()(base_model.output)
x_age = Dense(64, activation='relu')(x_age)
x_age = Dropout(0.2)(x_age)
output_age = Dense(1, activation='relu', name='age_output')(x_age)
age_model = Model(inputs=base_model.input, outputs=output_age)
age_model.compile(optimizer=Adam(learning_rate=0.0001), loss='mae', metrics=['mae'])
# Gender Model
x_gender = GlobalAveragePooling2D()(base_model.output)
x_gender = Dense(64, activation='relu')(x_gender)
x_gender = Dropout(0.2)(x_gender)
output_gender = Dense(1, activation='sigmoid', name='gender_output')(x_gender)
gender_model = Model(inputs=base_model.input, outputs=output_gender)
gender_model.compile(optimizer=Adam(learning_rate=0.0001), loss='binary_crossentropy', metrics=['accuracy'])
# Callbacks for Age Model
age_saver = ModelCheckpoint('age_model_weightsNone.h5', monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=True, mode='min')
age_early_stopping = EarlyStopping(monitor='val_loss', patience=8, verbose=1, mode='min')
# Callbacks for Gender Model
gender_saver = ModelCheckpoint('gender_model_weightsNone.h5', monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=True, mode='min')
gender_early_stopping = EarlyStopping(monitor='val_loss', patience=5, verbose=1, mode='min')
# Train the Age Model
print("Training Age Model")
history_age = age_model.fit(
X_train, Y_age_train,
batch_size=32,
validation_data=(X_test, Y_age_test),
epochs=100,
callbacks=[age_saver, age_early_stopping]
)
# Print the epoch number where Age Model training stopped
print(f"Age Model training stopped at epoch: {len(history_age.history['loss'])}")
# Train the Gender Model
print("Training Gender Model")
history_gender = gender_model.fit(
X_train, Y_gender_train,
batch_size=32,
validation_data=(X_test, Y_gender_test),
epochs=50,
callbacks=[gender_saver, gender_early_stopping]
)
# Print the epoch number where Gender Model training stopped
print(f"Gender Model training stopped at epoch: {len(history_gender.history['loss'])}")
# Plotting the training and validation loss for Age Model
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(history_age.history['loss'], label='Training Loss')
plt.plot(history_age.history['val_loss'], label='Validation Loss')
plt.title('Age Model Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
# Plotting the training and validation accuracy for Gender Model
plt.subplot(1, 2, 2)
plt.plot(history_gender.history['accuracy'], label='Training Accuracy')
plt.plot(history_gender.history['val_accuracy'], label='Validation Accuracy')
plt.title('Gender Model Training and Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.tight_layout()
plt.show()
# Eğitim ve doğrulama MAE grafikleri için Age Model
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.plot(history_age.history['loss'], label='Training Loss')
plt.plot(history_age.history['val_loss'], label='Validation Loss')
plt.title('Age Model Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.subplot(2, 2, 2)
plt.plot(history_age.history['mae'], label='Training MAE')
plt.plot(history_age.history['val_mae'], label='Validation MAE')
plt.title('Age Model Training and Validation MAE')
plt.xlabel('Epoch')
plt.ylabel('MAE')
plt.legend()
# Eğitim ve doğrulama kaybı grafikleri için Gender Model
plt.subplot(2, 2, 3)
plt.plot(history_gender.history['loss'], label='Training Loss')
plt.plot(history_gender.history['val_loss'], label='Validation Loss')
plt.title('Gender Model Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.subplot(2, 2, 4)
plt.plot(history_gender.history['accuracy'], label='Training Accuracy')
plt.plot(history_gender.history['val_accuracy'], label='Validation Accuracy')
plt.title('Gender Model Training and Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.tight_layout()
plt.show()
Training Age Model Epoch 1/100 WARNING:tensorflow:From C:\ProgramData\anaconda3\Lib\site-packages\keras\src\utils\tf_utils.py:492: The name tf.ragged.RaggedTensorValue is deprecated. Please use tf.compat.v1.ragged.RaggedTensorValue instead. WARNING:tensorflow:From C:\ProgramData\anaconda3\Lib\site-packages\keras\src\engine\base_layer_utils.py:384: The name tf.executing_eagerly_outside_functions is deprecated. Please use tf.compat.v1.executing_eagerly_outside_functions instead. 565/565 [==============================] - ETA: 0s - loss: 15.1321 - mae: 15.1321 Epoch 1: val_loss improved from inf to 14.67623, saving model to age_model_weightsNone.h5 565/565 [==============================] - 700s 1s/step - loss: 15.1321 - mae: 15.1321 - val_loss: 14.6762 - val_mae: 14.6762 Epoch 2/100 565/565 [==============================] - ETA: 0s - loss: 13.1961 - mae: 13.1961 Epoch 2: val_loss did not improve from 14.67623 565/565 [==============================] - 670s 1s/step - loss: 13.1961 - mae: 13.1961 - val_loss: 15.1534 - val_mae: 15.1534 Epoch 3/100 565/565 [==============================] - ETA: 0s - loss: 12.1696 - mae: 12.1696 Epoch 3: val_loss did not improve from 14.67623 565/565 [==============================] - 668s 1s/step - loss: 12.1696 - mae: 12.1696 - val_loss: 15.5600 - val_mae: 15.5600 Epoch 4/100 565/565 [==============================] - ETA: 0s - loss: 11.2705 - mae: 11.2705 Epoch 4: val_loss improved from 14.67623 to 12.11286, saving model to age_model_weightsNone.h5 565/565 [==============================] - 669s 1s/step - loss: 11.2705 - mae: 11.2705 - val_loss: 12.1129 - val_mae: 12.1129 Epoch 5/100 565/565 [==============================] - ETA: 0s - loss: 10.5111 - mae: 10.5111 Epoch 5: val_loss did not improve from 12.11286 565/565 [==============================] - 667s 1s/step - loss: 10.5111 - mae: 10.5111 - val_loss: 13.1318 - val_mae: 13.1318 Epoch 6/100 565/565 [==============================] - ETA: 0s - loss: 9.9529 - mae: 9.9529 Epoch 6: val_loss improved from 12.11286 to 11.91832, saving model to age_model_weightsNone.h5 565/565 [==============================] - 670s 1s/step - loss: 9.9529 - mae: 9.9529 - val_loss: 11.9183 - val_mae: 11.9183 Epoch 7/100 565/565 [==============================] - ETA: 0s - loss: 9.4809 - mae: 9.4809 Epoch 7: val_loss did not improve from 11.91832 565/565 [==============================] - 667s 1s/step - loss: 9.4809 - mae: 9.4809 - val_loss: 14.3454 - val_mae: 14.3454 Epoch 8/100 565/565 [==============================] - ETA: 0s - loss: 9.1006 - mae: 9.1006 Epoch 8: val_loss improved from 11.91832 to 9.61452, saving model to age_model_weightsNone.h5 565/565 [==============================] - 668s 1s/step - loss: 9.1006 - mae: 9.1006 - val_loss: 9.6145 - val_mae: 9.6145 Epoch 9/100 565/565 [==============================] - ETA: 0s - loss: 8.8274 - mae: 8.8274 Epoch 9: val_loss did not improve from 9.61452 565/565 [==============================] - 666s 1s/step - loss: 8.8274 - mae: 8.8274 - val_loss: 20.0299 - val_mae: 20.0299 Epoch 10/100 565/565 [==============================] - ETA: 0s - loss: 8.3789 - mae: 8.3789 Epoch 10: val_loss did not improve from 9.61452 565/565 [==============================] - 665s 1s/step - loss: 8.3789 - mae: 8.3789 - val_loss: 10.9089 - val_mae: 10.9089 Epoch 11/100 565/565 [==============================] - ETA: 0s - loss: 8.0545 - mae: 8.0545 Epoch 11: val_loss did not improve from 9.61452 565/565 [==============================] - 666s 1s/step - loss: 8.0545 - mae: 8.0545 - val_loss: 15.8874 - val_mae: 15.8874 Epoch 12/100 565/565 [==============================] - ETA: 0s - loss: 7.7073 - mae: 7.7073 Epoch 12: val_loss did not improve from 9.61452 565/565 [==============================] - 666s 1s/step - loss: 7.7073 - mae: 7.7073 - val_loss: 9.7073 - val_mae: 9.7073 Epoch 13/100 565/565 [==============================] - ETA: 0s - loss: 7.4322 - mae: 7.4322 Epoch 13: val_loss did not improve from 9.61452 565/565 [==============================] - 668s 1s/step - loss: 7.4322 - mae: 7.4322 - val_loss: 9.9594 - val_mae: 9.9594 Epoch 14/100 565/565 [==============================] - ETA: 0s - loss: 7.2002 - mae: 7.2002 Epoch 14: val_loss did not improve from 9.61452 565/565 [==============================] - 670s 1s/step - loss: 7.2002 - mae: 7.2002 - val_loss: 17.2538 - val_mae: 17.2538 Epoch 15/100 565/565 [==============================] - ETA: 0s - loss: 6.8610 - mae: 6.8610 Epoch 15: val_loss did not improve from 9.61452 565/565 [==============================] - 664s 1s/step - loss: 6.8610 - mae: 6.8610 - val_loss: 9.8214 - val_mae: 9.8214 Epoch 16/100 565/565 [==============================] - ETA: 0s - loss: 6.6277 - mae: 6.6277 Epoch 16: val_loss did not improve from 9.61452 565/565 [==============================] - 665s 1s/step - loss: 6.6277 - mae: 6.6277 - val_loss: 9.8045 - val_mae: 9.8045 Epoch 16: early stopping Age Model training stopped at epoch: 16 Training Gender Model Epoch 1/50 565/565 [==============================] - ETA: 0s - loss: 0.4686 - accuracy: 0.7668 Epoch 1: val_loss improved from inf to 0.52917, saving model to gender_model_weightsNone.h5 565/565 [==============================] - 692s 1s/step - loss: 0.4686 - accuracy: 0.7668 - val_loss: 0.5292 - val_accuracy: 0.7974 Epoch 2/50 565/565 [==============================] - ETA: 0s - loss: 0.3422 - accuracy: 0.8466 Epoch 2: val_loss improved from 0.52917 to 0.39497, saving model to gender_model_weightsNone.h5 565/565 [==============================] - 666s 1s/step - loss: 0.3422 - accuracy: 0.8466 - val_loss: 0.3950 - val_accuracy: 0.8006 Epoch 3/50 565/565 [==============================] - ETA: 0s - loss: 0.2849 - accuracy: 0.8730 Epoch 3: val_loss improved from 0.39497 to 0.35517, saving model to gender_model_weightsNone.h5 565/565 [==============================] - 668s 1s/step - loss: 0.2849 - accuracy: 0.8730 - val_loss: 0.3552 - val_accuracy: 0.8422 Epoch 4/50 565/565 [==============================] - ETA: 0s - loss: 0.2247 - accuracy: 0.9066 Epoch 4: val_loss did not improve from 0.35517 565/565 [==============================] - 665s 1s/step - loss: 0.2247 - accuracy: 0.9066 - val_loss: 0.3677 - val_accuracy: 0.8396 Epoch 5/50 565/565 [==============================] - ETA: 0s - loss: 0.1857 - accuracy: 0.9228 Epoch 5: val_loss did not improve from 0.35517 565/565 [==============================] - 669s 1s/step - loss: 0.1857 - accuracy: 0.9228 - val_loss: 0.4536 - val_accuracy: 0.8361 Epoch 6/50 565/565 [==============================] - ETA: 0s - loss: 0.1442 - accuracy: 0.9429 Epoch 6: val_loss did not improve from 0.35517 565/565 [==============================] - 665s 1s/step - loss: 0.1442 - accuracy: 0.9429 - val_loss: 0.5496 - val_accuracy: 0.8191 Epoch 7/50 565/565 [==============================] - ETA: 0s - loss: 0.1080 - accuracy: 0.9602 Epoch 7: val_loss did not improve from 0.35517 565/565 [==============================] - 666s 1s/step - loss: 0.1080 - accuracy: 0.9602 - val_loss: 0.5663 - val_accuracy: 0.8273 Epoch 8/50 565/565 [==============================] - ETA: 0s - loss: 0.0905 - accuracy: 0.9666 Epoch 8: val_loss did not improve from 0.35517 565/565 [==============================] - 667s 1s/step - loss: 0.0905 - accuracy: 0.9666 - val_loss: 0.5309 - val_accuracy: 0.8374 Epoch 8: early stopping Gender Model training stopped at epoch: 8
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, mean_absolute_error
import seaborn as sns
# [Veri yükleme ve işleme kodunuz buraya gelecek]
# ...
# Her yaş için kişi sayısını hesaplama
age_counts = {}
for age in ages_np:
if age in age_counts:
age_counts[age] += 1
else:
age_counts[age] = 1
# Yaşlara göre dağılımı sıralı bir şekilde almak
sorted_ages = sorted(age_counts.keys())
counts = [age_counts[age] for age in sorted_ages]
# Yaş Dağılım Grafiği
plt.figure(figsize=(15, 5))
plt.plot(sorted_ages, counts, marker='o')
plt.xlabel('Ages')
plt.ylabel('Number of Individuals')
plt.title('Age Distribution in the Dataset')
plt.grid(True)
plt.show()
def calculate_accuracies(ages, predictions):
age_accuracies = {}
for age in range(0, 120, 5):
correct = 0
total = 0
for i in range(len(ages)):
if age <= ages[i] < age + 5:
total += 1
if abs(predictions[i] - ages[i]) <= 5:
correct += 1
if total > 0:
accuracy = (correct / total) * 100
else:
accuracy = 0.0
age_accuracies[f'{age}-{age + 5}'] = accuracy
return age_accuracies
# Yas tahminlerini yap
y_pred_age = age_model.predict(X_test)
y_pred_age = y_pred_age.flatten()
# Doğruluk değerlerini hesapla
age_accuracies = calculate_accuracies(Y_age_test, y_pred_age)
# Her 5 yaş aralığı için doğruluk değerlerini yazdır
for age_range, accuracy in age_accuracies.items():
print(f'{age_range}: Accuracy = {accuracy:.2f}%')
def calculate_gender_accuracies(ages, genders, predictions):
gender_accuracies = {}
for age in range(0, 120, 5):
correct = 0
total = 0
for i in range(len(ages)):
if age <= ages[i] < age + 5:
total += 1
if abs(predictions[i] - genders[i]) <= 0.5:
correct += 1
if total > 0:
accuracy = (correct / total) * 100
else:
accuracy = 0.0
gender_accuracies[f'{age}-{age + 5}'] = accuracy
return gender_accuracies
# Cinsiyet tahminlerini yap
y_pred_gender = gender_model.predict(X_test)
y_pred_gender = (y_pred_gender > 0.5).astype(int)
# Doğruluk değerlerini hesapla
gender_accuracies = calculate_gender_accuracies(Y_age_test, Y_gender_test, y_pred_gender)
# Her 5 yaş aralığı için cinsiyet doğruluk değerlerini yazdır
for age_range, accuracy in gender_accuracies.items():
print(f'{age_range}: Accuracy = {accuracy:.2f}%')
# Yaş ve Cinsiyet Doğruluk Değerlerini Çiz
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
age_ranges = list(age_accuracies.keys())
accuracies_age = list(age_accuracies.values())
x_ticks = np.arange(0, 120, 5)
plt.barh(age_ranges, accuracies_age, color='skyblue')
plt.xticks(x_ticks)
plt.xlim(0, 100)
plt.xlabel('Accuracy (%)')
plt.ylabel('Age Range')
plt.title('Age Prediction Accuracy')
plt.subplot(1, 2, 2)
gender_ranges = list(gender_accuracies.keys())
accuracies_gender = list(gender_accuracies.values())
plt.barh(gender_ranges, accuracies_gender, color='salmon')
plt.xticks(x_ticks)
plt.xlim(0, 100)
plt.xlabel('Accuracy (%)')
plt.ylabel('Age Range')
plt.title('Gender Prediction Accuracy')
plt.tight_layout()
plt.show()
# Cinsiyet Modeli İçin Sınıflandırma Raporu
gender_model.load_weights('C:/Users/kasim.sahin/gender_model_weightsNone.h5')
y_pred_gender = gender_model.predict(X_test)
y_pred_gender = (y_pred_gender > 0.5).astype(int)
print("Gender Classification Report:")
print(classification_report(Y_gender_test, y_pred_gender))
# Yaş Tahmini İçin MAE
age_model.load_weights('C:/Users/kasim.sahin/age_model_weightsNone.h5')
y_pred_age = age_model.predict(X_test)
mae = mean_absolute_error(Y_age_test, y_pred_age)
print("Mean Absolute Error (MAE) for Age Prediction:", mae)
# Veri Setindeki Yaş Dağılımı
plt.figure(figsize=(10, 4))
sns.histplot(Y_age_test, bins=20, color='yellow', label='Actual Age', kde=True)
sns.histplot(y_pred_age, bins=20, color='brown', label='Predicted Age', kde=True)
for age in range(0, 117, 10):
plt.axvline(x=age, color='green', linestyle='--', linewidth=1, label=f'{age} years')
plt.title('Age Distribution in the Data Set')
plt.xlabel('Age')
plt.legend(loc='upper right')
plt.show()
# Yaş Tahminlerini Karşılaştırma Grafiği
fig, ax = plt.subplots()
ax.scatter(Y_age_test, y_pred_age.flatten()) # Adjusted with y_pred_age.flatten()
ax.plot([Y_age_test.min(), Y_age_test.max()], [Y_age_test.min(), Y_age_test.max()], 'k--', lw=4)
ax.set_xlabel('Actual Age')
ax.set_ylabel('Predicted Age')
plt.title('Actual vs Predicted Age')
plt.show()
189/189 [==============================] - 131s 690ms/step 0-5: Accuracy = 0.00% 5-10: Accuracy = 0.00% 10-15: Accuracy = 6.04% 15-20: Accuracy = 41.18% 20-25: Accuracy = 65.22% 25-30: Accuracy = 29.29% 30-35: Accuracy = 24.37% 35-40: Accuracy = 32.73% 40-45: Accuracy = 39.43% 45-50: Accuracy = 18.94% 50-55: Accuracy = 2.00% 55-60: Accuracy = 0.00% 60-65: Accuracy = 0.00% 65-70: Accuracy = 0.00% 70-75: Accuracy = 0.00% 75-80: Accuracy = 0.00% 80-85: Accuracy = 0.00% 85-90: Accuracy = 0.00% 90-95: Accuracy = 0.00% 95-100: Accuracy = 0.00% 100-105: Accuracy = 0.00% 105-110: Accuracy = 0.00% 110-115: Accuracy = 0.00% 115-120: Accuracy = 0.00% 189/189 [==============================] - 122s 644ms/step 0-5: Accuracy = 66.67% 5-10: Accuracy = 71.18% 10-15: Accuracy = 73.15% 15-20: Accuracy = 81.93% 20-25: Accuracy = 86.16% 25-30: Accuracy = 86.79% 30-35: Accuracy = 89.89% 35-40: Accuracy = 84.55% 40-45: Accuracy = 91.76% 45-50: Accuracy = 89.77% 50-55: Accuracy = 91.71% 55-60: Accuracy = 84.82% 60-65: Accuracy = 88.94% 65-70: Accuracy = 84.52% 70-75: Accuracy = 86.17% 75-80: Accuracy = 78.87% 80-85: Accuracy = 81.36% 85-90: Accuracy = 75.00% 90-95: Accuracy = 70.83% 95-100: Accuracy = 61.54% 100-105: Accuracy = 66.67% 105-110: Accuracy = 50.00% 110-115: Accuracy = 100.00% 115-120: Accuracy = 66.67%
189/189 [==============================] - 98s 516ms/step
Gender Classification Report:
precision recall f1-score support
0 0.84 0.87 0.85 3143
1 0.85 0.82 0.83 2884
accuracy 0.84 6027
macro avg 0.84 0.84 0.84 6027
weighted avg 0.84 0.84 0.84 6027
189/189 [==============================] - 92s 487ms/step
Mean Absolute Error (MAE) for Age Prediction: 9.614519504561677
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, mean_absolute_error
import seaborn as sns
# Her yaş için kişi sayısını hesaplama
age_counts = {}
for age in ages_np:
if age in age_counts:
age_counts[age] += 1
else:
age_counts[age] = 1
# Yaşlara göre dağılımı sıralı bir şekilde almak
sorted_ages = sorted(age_counts.keys())
counts = [age_counts[age] for age in sorted_ages]
# Yaş Dağılım Grafiği
plt.figure(figsize=(15, 5))
plt.plot(sorted_ages, counts, marker='o')
plt.xlabel('Ages')
plt.ylabel('Number of Individuals')
plt.title('Age Distribution in the Dataset')
plt.grid(True)
plt.show()
# Yaş ve Cinsiyet Doğruluk Değerlerini Çiz (Sadece Cinsiyet İçin)
plt.figure(figsize=(6, 6))
gender_ranges = list(gender_accuracies.keys())
accuracies_gender = list(gender_accuracies.values())
x_ticks = np.arange(1, 121, 5)
plt.barh(gender_ranges, accuracies_gender, color='salmon')
plt.xticks(x_ticks)
plt.xlim(0, 100)
plt.xlabel('Accuracy (%)')
plt.ylabel('Age Range')
plt.title('Gender Prediction Accuracy')
plt.show()
# Cinsiyet Modeli İçin Sınıflandırma Raporu
gender_model.load_weights('C:/Users/kasim.sahin/gender_model_weightsNone.h5')
y_pred_gender = gender_model.predict(X_test)
y_pred_gender = (y_pred_gender > 0.5).astype(int)
print("Gender Classification Report:")
print(classification_report(Y_gender_test, y_pred_gender))
# Yaş Tahmini İçin MAE
age_model.load_weights('C:/Users/kasim.sahin/age_model_weightsNone.h5')
y_pred_age = age_model.predict(X_test)
mae = mean_absolute_error(Y_age_test, y_pred_age)
print("Mean Absolute Error (MAE) for Age Prediction:", mae)
# Veri Setindeki Yaş Dağılımı
plt.figure(figsize=(10, 4))
sns.histplot(Y_age_test, bins=20, color='blue', label='Actual Age', kde=True)
sns.histplot(y_pred_age, bins=20, color='green', label='Predicted Age', kde=True)
for age in range(0, 120, 10):
plt.axvline(x=age, color='green', linestyle='--', linewidth=1, label=f'{age} years')
plt.title('Age Distribution in the Data Set')
plt.xlabel('Age')
plt.legend(loc='upper right')
plt.show()
# Yaş Tahminlerini Karşılaştırma Grafiği
fig, ax = plt.subplots()
ax.scatter(Y_age_test, y_pred_age.flatten()) # Adjusted with y_pred_age.flatten()
ax.plot([Y_age_test.min(), Y_age_test.max()], [Y_age_test.min(), Y_age_test.max()], 'k--', lw=4)
ax.set_xlabel('Actual Age')
ax.set_ylabel('Predicted Age')
plt.title('Actual vs Predicted Age')
plt.show()
189/189 [==============================] - 99s 523ms/step
Gender Classification Report:
precision recall f1-score support
0 0.84 0.87 0.85 3143
1 0.85 0.82 0.83 2884
accuracy 0.84 6027
macro avg 0.84 0.84 0.84 6027
weighted avg 0.84 0.84 0.84 6027
189/189 [==============================] - 99s 521ms/step
Mean Absolute Error (MAE) for Age Prediction: 9.614519504561677
def calculate_accuracy_within_3_years(y_true, y_pred):
correct = 0
total = len(y_true)
for actual_age, predicted_age in zip(y_true, y_pred):
lower_bound = predicted_age - 3
upper_bound = predicted_age + 3
if lower_bound <= actual_age <= upper_bound:
correct += 1
accuracy = (correct / total) * 100
return accuracy
# Age Model tahminleri
predicted_ages = age_model.predict(X_test).flatten()
# Tahminlerin doğruluğunu hesapla
accuracy_within_3_years = calculate_accuracy_within_3_years(Y_age_test, predicted_ages)
# Doğruluk oranını bas
print(f"Accuracy within 3 years: {accuracy_within_3_years}%")
# Doğruluk oranını gösteren grafik
plt.figure(figsize=(6, 4))
plt.bar(['Accuracy'], [accuracy_within_3_years])
plt.ylabel('Accuracy (%)')
plt.title('Prediction Accuracy Within 3 Years Age Range')
plt.ylim(0, 100)
plt.show()
def calculate_accuracy_within_3_years_per_age_group(y_true, y_pred, age_groups):
# Her yaş grubu için doğruluk oranlarını saklayacak sözlük
accuracy_per_group = {group: {'correct': 0, 'total': 0} for group in age_groups}
for actual_age, predicted_age in zip(y_true, y_pred):
# Hangi yaş grubuna ait olduğunu bul
age_group = min([group for group in age_groups if actual_age in group])
# 3 yıllık aralıkta doğru mu kontrol et
lower_bound = predicted_age - 3
upper_bound = predicted_age + 3
if lower_bound <= actual_age <= upper_bound:
accuracy_per_group[age_group]['correct'] += 1
accuracy_per_group[age_group]['total'] += 1
# Her yaş grubu için yüzde doğruluk hesapla, 0'a bölme hatasını önle
accuracy_percentages = {}
for group, values in accuracy_per_group.items():
if values['total'] > 0:
accuracy = (values['correct'] / values['total']) * 100
else:
accuracy = 'N/A' # Veri yok
accuracy_percentages[group] = accuracy
return accuracy_percentages
# Yaş gruplarını tanımla (0-120 arası 5'er yıllık dilimler)
age_groups = [range(i, i + 5) for i in range(1, 121, 5)]
# Age Model tahminleri
predicted_ages = age_model.predict(X_test).flatten()
# Her yaş grubu için doğruluk oranını hesapla
accuracy_per_age_group = calculate_accuracy_within_3_years_per_age_group(Y_age_test, predicted_ages, age_groups)
# Sonuçları bas
for age_group, accuracy in accuracy_per_age_group.items():
print(f"Age group {min(age_group)}-{max(age_group)}: {accuracy} accuracy")
# Sonuçları grafikte göster (N/A durumları hariç tut)
plt.figure(figsize=(16, 8))
plt.bar(range(len(accuracy_per_age_group)), [acc if isinstance(acc, float) else 0 for acc in accuracy_per_age_group.values()], align='center')
plt.xticks(range(len(accuracy_per_age_group)), [f"{min(group)}-{max(group)}" for group in age_groups])
plt.xlabel('Age Groups')
plt.ylabel('Accuracy (%)')
plt.title('Prediction Accuracy Within 3 Years for Each Age Group')
plt.show()
189/189 [==============================] - 101s 535ms/step Accuracy within 3 years: 27.044964327194293%
189/189 [==============================] - 101s 533ms/step Age group 1-5: 57.84023668639053 accuracy Age group 6-10: 11.842105263157894 accuracy Age group 11-15: 4.9079754601226995 accuracy Age group 16-20: 2.307692307692308 accuracy Age group 21-25: 13.07471264367816 accuracy Age group 26-30: 42.99212598425196 accuracy Age group 31-35: 44.205298013245034 accuracy Age group 36-40: 23.713646532438478 accuracy Age group 41-45: 17.037037037037038 accuracy Age group 46-50: 10.980392156862745 accuracy Age group 51-55: 13.114754098360656 accuracy Age group 56-60: 10.9375 accuracy Age group 61-65: 11.428571428571429 accuracy Age group 66-70: 9.448818897637794 accuracy Age group 71-75: 7.142857142857142 accuracy Age group 76-80: 2.7777777777777777 accuracy Age group 81-85: 8.47457627118644 accuracy Age group 86-90: 2.0 accuracy Age group 91-95: 0.0 accuracy Age group 96-100: 0.0 accuracy Age group 101-105: 0.0 accuracy Age group 106-110: 0.0 accuracy Age group 111-115: 0.0 accuracy Age group 116-120: 0.0 accuracy
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from sklearn.model_selection import train_test_split
# Set the path to the dataset
data_folder = "C:/yas_tahmini/UTKFaceee"
# Load and process the data
files = os.listdir(data_folder)
ages = []
genders = []
images = []
for file in files:
parts = file.split('_')
if len(parts) < 3 or not parts[0].isdigit() or not parts[1].isdigit():
continue
age, gender = map(int, parts[:2])
ages.append(age)
genders.append(gender)
ages_np = np.array(ages, dtype=np.float32)
genders_np = np.array(genders, dtype=np.float32)
# Function to process and return a single image
def process_image(file):
full_path = os.path.join(data_folder, file)
image = cv2.imread(full_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (224, 224))
image = image.astype(np.float32) / 255
return image
# Test Specific Images Function
def test_specific_images(indices, age_model, gender_model):
for index in indices:
if 0 <= index < len(files):
file = files[index]
actual_age, actual_gender = ages_np[index], genders_np[index]
actual_age = int(actual_age) # Yaşı tam sayıya dönüştür
actual_gender_str = 'Female' if actual_gender == 1 else 'Male'
image = process_image(file)
plt.imshow(image)
plt.title(f"Filename: {file}")
plt.show()
age_pred = age_model.predict(np.array([image]))
gender_pred = gender_model.predict(np.array([image]))
predicted_age = int(np.round(age_pred[0]))
predicted_gender = 'Female' if int(np.round(gender_pred[0])) == 1 else 'Male'
print(f"Actual Age: {actual_age}, Actual Gender: {actual_gender_str}")
print(f"Predicted Age: {predicted_age}, Predicted Gender: {predicted_gender}")
else:
print(f"Index {index} is out of range. Valid range is 0 to {len(files) - 1}")
# Load your models (age_model and gender_model)
# Make sure to load or define your models here
# Test the models with specific indices
specific_indices = [52, 615, 650, 549, 4961, 2537, 2902, 278, 1451, 3001, 1904, 181, 5472]
test_specific_images(specific_indices, age_model, gender_model)
1/1 [==============================] - 0s 153ms/step 1/1 [==============================] - 0s 146ms/step Actual Age: 10, Actual Gender: Male Predicted Age: 35, Predicted Gender: Female
1/1 [==============================] - 0s 164ms/step 1/1 [==============================] - 0s 144ms/step Actual Age: 14, Actual Gender: Female Predicted Age: 28, Predicted Gender: Female
1/1 [==============================] - 0s 150ms/step 1/1 [==============================] - 0s 158ms/step Actual Age: 15, Actual Gender: Male Predicted Age: 34, Predicted Gender: Male
1/1 [==============================] - 0s 119ms/step 1/1 [==============================] - 0s 170ms/step Actual Age: 14, Actual Gender: Male Predicted Age: 31, Predicted Gender: Male
1/1 [==============================] - 0s 125ms/step 1/1 [==============================] - 0s 154ms/step Actual Age: 24, Actual Gender: Female Predicted Age: 29, Predicted Gender: Female
1/1 [==============================] - 0s 156ms/step 1/1 [==============================] - 0s 172ms/step Actual Age: 1, Actual Gender: Female Predicted Age: 1, Predicted Gender: Male
1/1 [==============================] - 0s 123ms/step 1/1 [==============================] - 0s 141ms/step Actual Age: 20, Actual Gender: Male Predicted Age: 30, Predicted Gender: Male
1/1 [==============================] - 0s 156ms/step 1/1 [==============================] - 0s 185ms/step Actual Age: 12, Actual Gender: Male Predicted Age: 28, Predicted Gender: Male
1/1 [==============================] - 0s 136ms/step 1/1 [==============================] - 0s 152ms/step Actual Age: 18, Actual Gender: Female Predicted Age: 32, Predicted Gender: Female
1/1 [==============================] - 0s 145ms/step 1/1 [==============================] - 0s 140ms/step Actual Age: 20, Actual Gender: Female Predicted Age: 31, Predicted Gender: Female
1/1 [==============================] - 0s 165ms/step 1/1 [==============================] - 0s 164ms/step Actual Age: 1, Actual Gender: Male Predicted Age: 1, Predicted Gender: Female
1/1 [==============================] - 0s 161ms/step 1/1 [==============================] - 0s 150ms/step Actual Age: 110, Actual Gender: Female Predicted Age: 38, Predicted Gender: Male
1/1 [==============================] - 0s 145ms/step 1/1 [==============================] - 0s 133ms/step Actual Age: 25, Actual Gender: Male Predicted Age: 32, Predicted Gender: Male
import cv2
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.models import Model
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import Input, GlobalAveragePooling2D, Dense
# Age ve Gender Model'lerini yeniden oluşturun ve ağırlıkları yükleyin
# Age Model
base_model_age = ResNet50(weights='imagenet', include_top=False, input_tensor=Input(shape=(224, 224, 3)))
x_age = GlobalAveragePooling2D()(base_model_age.output)
x_age = Dense(64, activation='relu')(x_age)
output_age = Dense(1, activation='relu', name='age_output')(x_age)
age_model = Model(inputs=base_model_age.input, outputs=output_age)
age_model.load_weights('age_model_weightsNone.h5') # Yolun doğru olduğundan emin olun
# Gender Model
base_model_gender = ResNet50(weights='imagenet', include_top=False, input_tensor=Input(shape=(224, 224, 3)))
x_gender = GlobalAveragePooling2D()(base_model_gender.output)
x_gender = Dense(64, activation='relu')(x_gender)
output_gender = Dense(1, activation='sigmoid', name='gender_output')(x_gender)
gender_model = Model(inputs=base_model_gender.input, outputs=output_gender)
gender_model.load_weights('gender_model_weightsNone.h5') # Yolun doğru olduğundan emin olun
# Resim tahmini fonksiyonunu tanımla
def external_test_image(image_path, age_model, gender_model):
# Resmi yükle ve boyutlandır
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (224, 224))
# Resmi göster
plt.imshow(image)
plt.title(f"Test Image: {image_path}")
plt.show()
# Normalize et ve tahmin yap
image = np.array(image) / 255.0
age_pred = age_model.predict(np.array([image]))
gender_pred = gender_model.predict(np.array([image]))
# Tahminleri al ve yazdır
predicted_age = int(np.round(age_pred[0][0]))
predicted_gender = 'Female' if int(np.round(gender_pred[0][0])) == 1 else 'Male'
print(f"Predicted Age: {predicted_age}, Predicted Gender: {predicted_gender}")
# Test resimleri
test_images = [
'C:/yas_tahmini/kasim.jpg',
'C:/yas_tahmini/ali_ihsan.jpg',
'C:/yas_tahmini/kasim.jpg',
'C:/yas_tahmini/ali_ihsan.jpg',
'C:/yas_tahmini/serdar.jpg',
'C:/yas_tahmini/kasim2.jpg',
'C:/yas_tahmini/kasim3.jpg',
'C:/yas_tahmini/kasim4.jpg',
'C:/yas_tahmini/kasim5.jpg',
'C:/yas_tahmini/kasim6.jpg',
'C:/yas_tahmini/ali_ihsan2.jpg',
'C:/yas_tahmini/fuat.jpg',
'C:/yas_tahmini/osman.jpg',
'C:/yas_tahmini/ozge.jpg',
'C:/yas_tahmini/ozgur.jpg',
'C:/yas_tahmini/emre_sumer.jpg',
'C:/yas_tahmini/didem_olcer.jpg',
'C:/yas_tahmini/mustafa_sert.jpg',
'C:/yas_tahmini/merve.jpg',
'C:/yas_tahmini/ali_ihsan3.jpeg',
]
# Her resim için tahmin yap
for img_path in test_images:
external_test_image(img_path, age_model, gender_model)
1/1 [==============================] - 4s 4s/step 1/1 [==============================] - 4s 4s/step Predicted Age: 29, Predicted Gender: Male
1/1 [==============================] - 0s 235ms/step 1/1 [==============================] - 0s 295ms/step Predicted Age: 43, Predicted Gender: Male
1/1 [==============================] - 0s 249ms/step 1/1 [==============================] - 0s 322ms/step Predicted Age: 29, Predicted Gender: Male
1/1 [==============================] - 0s 272ms/step 1/1 [==============================] - 0s 312ms/step Predicted Age: 43, Predicted Gender: Male
1/1 [==============================] - 0s 248ms/step 1/1 [==============================] - 0s 280ms/step Predicted Age: 51, Predicted Gender: Male
1/1 [==============================] - 0s 344ms/step 1/1 [==============================] - 0s 254ms/step Predicted Age: 29, Predicted Gender: Male
1/1 [==============================] - 0s 265ms/step 1/1 [==============================] - 0s 250ms/step Predicted Age: 58, Predicted Gender: Male
1/1 [==============================] - 0s 266ms/step 1/1 [==============================] - 0s 225ms/step Predicted Age: 59, Predicted Gender: Male
1/1 [==============================] - 0s 136ms/step 1/1 [==============================] - 0s 120ms/step Predicted Age: 32, Predicted Gender: Male
1/1 [==============================] - 0s 125ms/step 1/1 [==============================] - 0s 151ms/step Predicted Age: 32, Predicted Gender: Male
1/1 [==============================] - 0s 126ms/step 1/1 [==============================] - 0s 153ms/step Predicted Age: 44, Predicted Gender: Male
1/1 [==============================] - 0s 155ms/step 1/1 [==============================] - 0s 123ms/step Predicted Age: 34, Predicted Gender: Male
1/1 [==============================] - 0s 153ms/step 1/1 [==============================] - 0s 150ms/step Predicted Age: 64, Predicted Gender: Male
1/1 [==============================] - 0s 145ms/step 1/1 [==============================] - 0s 137ms/step Predicted Age: 32, Predicted Gender: Female
1/1 [==============================] - 0s 152ms/step 1/1 [==============================] - 0s 169ms/step Predicted Age: 30, Predicted Gender: Male
1/1 [==============================] - 0s 150ms/step 1/1 [==============================] - 0s 159ms/step Predicted Age: 33, Predicted Gender: Male
1/1 [==============================] - 0s 158ms/step 1/1 [==============================] - 0s 122ms/step Predicted Age: 33, Predicted Gender: Female
1/1 [==============================] - 0s 161ms/step 1/1 [==============================] - 0s 150ms/step Predicted Age: 33, Predicted Gender: Male
1/1 [==============================] - 0s 129ms/step 1/1 [==============================] - 0s 140ms/step Predicted Age: 36, Predicted Gender: Female
1/1 [==============================] - 0s 154ms/step 1/1 [==============================] - 0s 150ms/step Predicted Age: 34, Predicted Gender: Male